#include "kernel/types.h"
#include "kernel/stat.h"
#include "kernel/param.h"
#include "user/user.h"

int main(int argc, char *argv[]) {
    char buf[512];
    char* new_argv[MAXARG];
    char tmp_argv[MAXARG][16];
    int i, buf_size;
    for (i = 1; i < argc; i++) {
        new_argv[i - 1] = argv[i];
    }
    int offset = 0;
    while ((buf_size = read(0, buf + offset, (sizeof buf) - offset)) != 0) {
        offset += buf_size;
    }
    buf_size = offset;
    int now = 0;
    int j = 0;
    for (i = 0; i < buf_size; i++) {
        if (buf[i] == '\n') {
            tmp_argv[now][j + 1] = 0;
            new_argv[argc + now - 1] = tmp_argv[now];
            new_argv[argc + now] = 0;
            if (fork() == 0) {
                exec(new_argv[0], new_argv);
                printf("xargs exec %s failed", new_argv[0]);
            }
            now = 0;
            j = 0;
            wait(0);
            continue;
        }

        if (buf[i] == ' ') {
            tmp_argv[now][j + 1] = 0;
            new_argv[argc + now - 1] = tmp_argv[now];
            now ++;
            j = 0;
        } else {
            tmp_argv[now][j ++] = buf[i];
        }
    }
    exit(0);
}
